package com.skcc.cop.mrtaxi.biz.destination;

import java.util.ArrayList;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.Toast;

import com.skcc.cop.mrtaxi.BaseActivity;
import com.skcc.cop.mrtaxi.R;
import com.skcc.cop.mrtaxi.biz.HomeListActivity;
import com.skcc.cop.mrtaxi.biz.IntroActivity;
import com.skcc.cop.mrtaxi.util.CalendarUtil;
import com.skcc.cop.mrtaxi.view.TitleBar;
import com.skcc.cop.mrtaxi.view.TitleBar.OnTitleBarEventListener;
import com.skp.Tmap.TMapPOIItem;
import com.skp.Tmap.TMapView;

public class AddDestinationActivity extends BaseActivity implements OnClickListener, OnTitleBarEventListener{

	

	private static final String TAG = AddDestinationActivity.class.getSimpleName();
	private ImageButton mBackImageButton;
	// private EditText mAddress1EditText, mAddress2EditText, mAddress3EditText;
	private EditText mPassengerEditText;
	private FrameLayout mAddButton, mResetButton;
	private AutoCompleteTextView mAddressAutoCompleteTextView;
	private String destination = "";
	private Double Lati = 0.0;
	private Double Long = 0.0;
	private TitleBar mTitleBarView;

	private PlacesAutoCompleteAdapter autoAdapter1;

	private TMapView mMapView = null;	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_destination_add);

		mTitleBarView = (TitleBar) this.findViewById(R.id.titlebar_view);
		mTitleBarView.setEventListener(this);
		mTitleBarView.showBack();
		mTitleBarView.setTitle(R.string.destination_add);
		
		//mBackImageButton = (ImageButton)findViewById(R.id.destination_add_back_imageButton);
		mPassengerEditText = (EditText)findViewById(R.id.destination_add_passenger_editText);
		
		mAddButton = (FrameLayout)findViewById(R.id.destination_add_add_frame);
		mResetButton = (FrameLayout)findViewById(R.id.destination_add_reset_frame);

		//mBackImageButton.setOnClickListener(this);
		mAddButton.setOnClickListener(this);
		mResetButton.setOnClickListener(this);

		mMapView = new TMapView(this);

		configureMapView();
		autoComplete();

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

		if (v.getId() == R.id.destination_add_reset_frame){
			mAddressAutoCompleteTextView.setText("");
			mPassengerEditText.setText("");

		//등록
		}else if (v.getId() == R.id.destination_add_add_frame){
			
			Editable editText = mAddressAutoCompleteTextView.getText();
			String selectText = editText.toString();
			
			
			
			if(selectText.length() == 0){
				
				Toast.makeText(AddDestinationActivity.this, "주소를 입력해주세요.", Toast.LENGTH_SHORT).show();
				
				
			}else{
				
				if(mPassengerEditText.getText() == null || mPassengerEditText.getText().equals("") || mPassengerEditText.getText().length()==0){
					
					Toast.makeText(AddDestinationActivity.this, "인원을 입력해주세요.", Toast.LENGTH_SHORT).show();
					
				}else{
					
					selectItem();
					
					if(EntityValidation()){
						dataBaseControl.insertDestination(makeEntity());
						Intent intent = new Intent(AddDestinationActivity.this, ManageDestinationActivity.class);
				        startActivity(intent);
						finish();
					}else{
						Toast.makeText(AddDestinationActivity.this, "목적지 정보를 다시 입력해주세요.", Toast.LENGTH_SHORT).show();
					}
					
				}

			}

		}
	}

	private DestinationEntity makeEntity(){
		String regTime = CalendarUtil.getTodayTimeString();
		DestinationEntity destinationEntity = new DestinationEntity();
		destinationEntity.setAddress1(destination);
		if(!"".equals(mPassengerEditText.getText()))
			destinationEntity.setPassenger(Integer.parseInt(mPassengerEditText.getText().toString()));
			destinationEntity.setRegTime(regTime);

		//목적지 좌표추가
		destinationEntity.setLati(Lati);
		destinationEntity.setLongi(Long);
		//목적지 Accuracy
		//destinationEntity.setAccuracy();	
		return destinationEntity;

	}
	
	private boolean EntityValidation(){
	
		if("".equals(destination)){
			Toast.makeText(AddDestinationActivity.this, "목적지가 없습니다.", Toast.LENGTH_SHORT).show();
			return false;
		}
		if("".equals(mPassengerEditText.getText())){
			Toast.makeText(AddDestinationActivity.this, "인원정보가 없습니다.", Toast.LENGTH_SHORT).show();
			return false;
		}
		if("".equals(Lati)){
			Toast.makeText(AddDestinationActivity.this, "위치정보가 없습니다.", Toast.LENGTH_SHORT).show();
			return false;
		}
		if("".equals(Long)){
			Toast.makeText(AddDestinationActivity.this, "위치정보가 없습니다.", Toast.LENGTH_SHORT).show();
			return false;
		}
		return true;
		
	}


	private void autoComplete() {
		// TODO Auto-generated method stub

		//AutoComplete
		mAddressAutoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.destination_add_address1_autoCompleteTextView);
		autoAdapter1  = new PlacesAutoCompleteAdapter(this, R.layout.list_item);
		mAddressAutoCompleteTextView.setAdapter(autoAdapter1);

		//Toast.makeText(DestinationAddActivity.this, autoCompView1.getText(), Toast.LENGTH_SHORT).show();
	}

	private void configureMapView() {

		new Thread() {
			@Override
			public void run() {		
				////SDK 인증키
				mMapView.setSKPMapApiKey("61df72e4-9a68-3b16-92ad-94c7356f5ed9");					
				mMapView.setLanguage(mMapView.LANGUAGE_KOREAN);		
			}
		}.start();

	}


	private void selectItem() {
		// TODO Auto-generated method stub

		Editable editText = mAddressAutoCompleteTextView.getText();
		String selectText = editText.toString();

		Log.i(TAG, "selectText = " + selectText);
		
			
			if(selectText.length() > 0){

				//autoAdapter1.findAllPoi(selectText);
				//autoAdapter1.findAddressPoi(selectText);
				TMapPOIItem item = null;

				//TMapPOIItem 이거를 STring으로 안받는 이유가.. TMapPOIItem안에 map으로 이루어져있음.
				ArrayList<TMapPOIItem> tempList = new ArrayList<TMapPOIItem>();
				tempList.clear();
				tempList = autoAdapter1.gettMapList();
				if(tempList != null && tempList.size() > 0){

					//for문 돌려서 autoComplete에 있는 목록 뽑아와서 내가 선택한 명칭과 비교..
					for(int i=0; i < tempList.size(); i++){			
						TMapPOIItem tempItem = tempList.get(i);
//						Log.i(TAG, tempItem.desc);
//						Log.i(TAG, tempItem.id);
//						Log.i(TAG, tempItem.getPOIAddress());
//						Log.i(TAG, tempItem.getPOIName());
						
						if(selectText.equals(tempItem.name)){				
							item = tempItem;
							Log.i(TAG, "Lati = " + item.getPOIPoint().getLatitude());
							Log.i(TAG, "Long = " + item.getPOIPoint().getLongitude());
							break;
						}
					}

					try{
						//명칭
						destination = item.name;
						//위도
						Lati = item.getPOIPoint().getLatitude();
						//경도
						Long = item.getPOIPoint().getLongitude();

						if(Lati== null || Double.toString(Lati).length() == 0 || Double.toString(Lati) == ""){
							Toast.makeText(AddDestinationActivity.this, "찾고자 하는 주소가 없습니다."+ "\n" + " 다른 명칭으로 입력해 주세요.", Toast.LENGTH_SHORT).show();
							return;
						}else{
							
							Toast.makeText(AddDestinationActivity.this, destination + "\n" + Lati + "\n" + Long, Toast.LENGTH_SHORT).show();
						}
						

					}catch(NullPointerException e){

						Toast.makeText(AddDestinationActivity.this, "찾고자 하는 주소가 없습니다."+ "\n" + " 다른 명칭으로 입력해 주세요.", Toast.LENGTH_SHORT).show();
						e.getStackTrace();
					}
				}

			}else{

				Toast.makeText(AddDestinationActivity.this, "찾고자 하는 주소가 없습니다."+ "\n" + " 다른 명칭으로 입력해 주세요.", Toast.LENGTH_SHORT).show();

			}
			
	}

	@Override
	public void onBackClicked() {
		// TODO Auto-generated method stub
		
		if(haveUserDestination()){
			
			finish();
			
		}else{
			
			Toast.makeText(AddDestinationActivity.this, "적어도 하나 이상의 목적지를 등록해야 합니다.", Toast.LENGTH_SHORT).show();
			return;
		}
		
	}

	@Override
	public void onAddClicked() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub

		
	}
	
}
